<?php
require_once 'Jssdk.class.php';
/**
 * Created by PhpStorm.
 * User: maomao
 * Date: 2016/11/29
 * Time: 14:19
 */

class Weixin extends Jssdk
{
	public $openid;
	static public $Name;//微信变量名称
	static public $Server;//online --线上 localhost --本地
	static public $Host;//线上授权地址
	static public $obj = NULL;
	function __construct($appId = '',$appSecret = '',$name = 'wechat',$server = 'online'){
		self::$Name 	= $name;
		self::$Server 	= $server;
		
		if( ! $appId || ! $appSecret){
			if ( ! defined('APPID') || ! defined('APPSECRET')){
				throw new ErrorException("请设置Weixin参数[APPID,APPSECRET]");
			}
			$this->appId = APPID;
			$this->appSecret = APPSECRET;
		}else{
			$this->appId = $appId;
			$this->appSecret = $appSecret;
		}
	}
	
	/**
	 * 单列模式入口
	 * @return Weixin
	 */
	static public function getWechat(){
	    if ( ! self::$obj instanceof self){
	        self::$obj = new self();
	    }
	    return self::$obj;
	}
	
	/**
	 * 设置中转服务器授权地址
	 * @param unknown $host
	 */
	public function setHost($host){
		self::$Host = $host;
	}
	
	/**
	 * 授权获取openid
	 * @return string|unknown
	 */
    public function get_openid()
    {
    	if(empty($_COOKIE[self::$Name])){
    		//如果带参数
    		if( ! empty($_REQUEST[self::$Name])){
    			$openid = $_REQUEST[self::$Name];
            }
            if(empty($openid)){
            	//切换本地与线上授权
            	if (self::$Server === 'localhost'){
            		$code = $this->code_to_host();
            	}elseif (self::$Server === 'online'){
            		$code = $this->get_oauth2_code();
            	}
                $openid = $this->get_oauth2_openid($code);

            }
            setcookie(self::$Name,$openid,time()+3600*24,'/');
            $this->openid = $openid;
            return $openid;
        }else{
        	$this->openid = $_COOKIE[self::$Name];

        	return $_COOKIE[self::$Name];
        }
    }

    /**
     * @return mixed 获取code
     */
    private function code_to_host()
    {
        //$host="http://www.szrmax.cc/index.php?s=/wap/Login/wechat.html";

        if(empty($_GET['code']))
        {
        	//当前本地地址，作为回调
//            $redirect_uri = urlencode($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $redirect_uri = urlencode($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING']);
            $redirect_uri = str_replace('index.php%2F', '', $redirect_uri);

            if(strpos(self::$Host, '?') === false){
//                p("location:".self::$Host."?return_url=".$redirect_uri);
	            header("location:".self::$Host."?return_url=".$redirect_uri); // URL参数名不能 redirect_uri 会与微信冲突
            }else{
	            header("location:".self::$Host."&return_url=".$redirect_uri); // URL参数名不能 redirect_uri 会与微信冲突
            }
            exit();
        }
        else{
            return $_GET['code'];
        }
    }

    /**
     * 发送code到访问请求的地址
     * @param $code
     */
    public function send_code_self()
    {
    	$code = $this->get_oauth2_code();
        if( ! empty($code)){
            //检查
        	if(strpos($_REQUEST['url'],'?') === FALSE){
                header("location:http://".$_REQUEST['url']."?code=".$code);
            }
            else{
                header("location:http://".$_REQUEST['url']."&code=".$code);
            }
        }
    }

    /**
     * 获取微信code
     */
    public function get_oauth2_code()
    {
        if(empty($_GET['code']))
        {
//             $redirect_uri = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $redirect_uri = urlencode(base_url().uri_string().'?'.$_SERVER['QUERY_STRING']);
            $para = array(
                "appid"         => APPID,
                "redirect_uri"  => $redirect_uri,
                "response_type" => 'code',
                "scope"         => 'snsapi_userinfo',
                "state"         => '123#wechat_redirect'
            );
            //snsapi_base 无需点击授权
            //snsapi_userinfo 点击授权
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$para['redirect_uri']."&response_type=code&scope=".$para['scope']."&state=123#wechat_redirect";
            header("location:".$url);
            exit;
        }
        else{
            return $_GET['code'];
        }
    }

    /**
     * 获取微信openid
     * @param $code
     * @return string
     */
    public function get_oauth2_openid($code){

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        $rets =  $this->curl_get_contents($url);
        $ret_arr = json_decode($rets,true);
        if(!empty($ret_arr['openid'])){
            return  $ret_arr['openid'];
        }
        else{
            return 'null';
        }
    }

    /**
     * 获取用户信息
     * @param $wechatid 用户openid
     * @return mixed  返回用户信息
     */
    public function get_user_info($openid){

    	
    	if(!empty($openid))
        {
//        	$access_token = $this->getAccessToken();
            $access_token = file_get_contents('http://readyforgoing.com/gebi/access_token.php');
            $access_token = json_decode($access_token, true);
            $access_token = $access_token['access_token'];
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
            $res_json = $this->curl_get_contents($url);
            $w_user = json_decode($res_json,TRUE);
            $w_user['access_token']=$access_token;//设置token
            //抛出获取用户详细信息时的错误
            if(!empty($w_user['errcode']))
            {
                if($w_user['errcode']== '40003')
                {
                    echo "ERROR:openid error!";
                    exit();
                }
            }
            return $w_user;
        }
    }

    /**
     * 从微信服务器 下载资源	
     * @param $media_id		资源数组
     * @param $path			路径
     * @param $filename		图片名称
     * @param $type			类型 jpg
     * @return string		
     */
    public function downloadMEDIA($media_id,$path,$filename = '',$type = 'jpg'){

        if(!file_exists($path)){
            mkdir($path,0777,true);
        }

        $data=array();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->getAccessToken()."&media_id=";
        foreach ($media_id as $k=>$v){
            $fname = '';
        	if( ! $filename){
	            $fname = $k;
        	}else{
                $fname = $filename.'_'.$k;
            }
        	
            $Turl=$url.$v;
            $ch=curl_init($Turl);
            $fname = $path.'/'.$fname.'.'.$type;
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            $image=curl_exec($ch);
            if(empty($image)){
                break;
            }
            $tp=fopen($fname,'w');
            fwrite($tp,$image);
            fclose($tp);
            $data[$k]=$fname;
        }
        return $data;
    }
    
    
}
